package com.sxh.user.Utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TokenUtil {
    //获取请求中的Token
    public static String getToken() {
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return null;
        }
        //从Authorization头获取 (格式: Bearer token)
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7); // 去掉"Bearer "前缀
        }
//        // 2. 从token参数获取 (适用于GET请求或表单提交)
//        String tokenParam = request.getParameter("token");
//        if (tokenParam != null && !tokenParam.isEmpty()) {
//            return tokenParam;
//        }
        return null;
    }

    /**
     * 获取当前请求对象
     */
    private static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
}
